//
//  NSDate+Extension.swift
//  weibopush
//
//  Created by 龚欣 on 15/7/12.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit

extension NSDate {
    
    func sinaDateWithString(string : String) -> NSDate{
        //"Sun Jul 12 10:24:17 +0800 2015"
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEE MMM dd HH:mm:ss zzzz yyyy"
        formatter.locale = NSLocale(localeIdentifier: "en")
        
        return formatter.dateFromString(string) ?? NSDate()
        
    }
    
    /**
    返回当前日期的描述信息，格式如下：
    
    刚刚(一分钟内)
    X分钟前(一小时内)
    X小时前(当天)
    昨天 HH:mm(昨天)
    MM-dd HH:mm(一年内)
    yyyy-MM-dd HH:mm(更早期)
    */
    
    func dateDescription() -> String{
        let calender = NSCalendar.currentCalendar()
        
        if calender.isDateInToday(self){
            let delat  = Int(NSDate().timeIntervalSinceDate(self))
            if delat < 60 {
                return "刚刚"
            }
            if delat < 60 * 60 {
                return "\(delat/60) 分钟前"
            }
            if delat < 24 * 60 * 60{
                return "\(delat/3600) 小时前"
            }
        }
        
        var fmtString = "HH:mm"
        if calender.isDateInYesterday(self){
            fmtString = "昨天" + fmtString
        
        }else {
            fmtString = "MM-dd " + fmtString
            
            let component = calender.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
            if component.year != 0 {
                print(component.year)
               fmtString = "yyyy-" + fmtString
            }
        }
        
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en")
        formatter.dateFormat = fmtString
        
        return formatter.stringFromDate(self)
    }

}
